package com.faxe.letsgroup.ws.daohibernate;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.springframework.dao.support.DataAccessUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.faxe.letsgroup.ws.dao.GenericDAO;

@Repository
public abstract class GenericDAOHibernate<T> extends DaoSupport implements GenericDAO<T> 
{	

	private Class<T> type;
	
	protected Class<T> getType()
	{
		return this.type;
	}
	
	protected String getClassName()
	{
		return type.getName();
	}

	@SuppressWarnings("unchecked")
	public GenericDAOHibernate()
	{
		Type t = getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) t;
		type = (Class)pt.getActualTypeArguments()[0];
	}

	@Override
	public void delete(T obj)
	{
		getSession().delete(obj);
	}

	@Override
	public T find (Integer id)
	{
		return (T)getHibernateTemplate().get(type, id);
	}

	@Transactional(readOnly=false, propagation = Propagation.REQUIRED)
	public void save (T obj)
	{
		getHibernateTemplate().saveOrUpdate(obj);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll()
	{
		return (List<T>)getHibernateTemplate().find("FROM " + type.getName());
	}
	
	@Override
	public Integer countAll()
	{
		return DataAccessUtils.intResult(getHibernateTemplate().find("select count(*) from " + type.getName()));
	}
	
}

